# -*- coding: UTF-8 -*-
#!/usr/local/bin/python

#Copyright (C) 2011 by raptor
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# convert wordpress blog to epub
# author  : raptor@we8log.com
# created : 2011/08/16


import os
import sys
import getopt
import re
from datetime import datetime
from lxml import etree
from epubbuilder import EpubData
import traceback


pat_imgurls = re.compile(u"<img[^>]*src=[\'\"]?([^\'\s>\"]*)[\'\"\s>]", re.I | re.S)
pat_imgname = re.compile("http.*?/[0-9]{5}-([^/]*)$", re.I | re.S)


class BlogWordPress:

    def __init__(self, src_dir):
        self.src_dir = src_dir
        f = open(os.path.join(src_dir, "wordpress.xml"), "r")
        c = f.read()
        f.close()
        self.root = etree.fromstring(c)

    def _get_text(self, node):
        if len(node) > 0:
            return node[0].text
        else:
            return str(node)

    def _format_post(self, body):
        body = body.replace(u"\n\n", u"</p><p>")
        body = body.replace(u"\n", u"<br/>")
        return body

    def _imgurlrep(self, body):
        m = pat_imgurls.findall(body)
        for url in m:
            try:
                imgname = pat_imgname.findall(url)[0]
                body = body.replace(url, "images/%s" % imgname)
            except:
                continue
        return body

    def _get_bloginfo(self):
        title  = self._get_text(self.root.xpath("/rss/channel/title"))
        url    = self._get_text(self.root.xpath("/rss/channel/link"))
        author = self._get_text(self.root.xpath("/rss/channel/item[1]/dc:creator", namespaces=self.root.nsmap))
        return dict(title=title, url=url, author=author)

    def _format_chapter(self, chp):
        title    = self._get_text(chp.xpath("title"))
        created  = self._get_text(chp.xpath("wp:post_date", namespaces=self.root.nsmap))
        postbody = self._get_text(chp.xpath("content:encoded", namespaces=self.root.nsmap))
        postbody = self._format_post(postbody)
        postbody = self._imgurlrep(postbody)
        postbody = "<h2>%s</h2><div class='post'><p>%s</p></div><p class='postfoot'>%s</p>" % (title, postbody, created)
        comments = chp.xpath("wp:comment", namespaces=self.root.nsmap)
        commbody = u"<h3>评论</h3>"
        for comm in comments:
            ccreated = self._get_text(comm.xpath("wp:comment_date", namespaces=self.root.nsmap))
            cname    = self._get_text(comm.xpath("wp:comment_author", namespaces=self.root.nsmap))
            ccontent = self._get_text(comm.xpath("wp:comment_content", namespaces=self.root.nsmap))
            commbody += u"<h4>--&nbsp;<span>%s</span>&nbsp;by&nbsp;<span>%s</span></h4>%s" % (cname, ccreated, ccontent)
        return "%s%s%s-%s" % (created[2:4], created[5:7], created[8:10], title), postbody + commbody

    def _exportchapters(self, epub):
        chapters = self.root.xpath("/rss/channel/item")
        for chp in chapters:
            if self._get_text(chp.xpath("wp:status", namespaces=self.root.nsmap)) != 'publish':
                continue
            fid = -1
            try:
                fid = int(self._get_text(chp.xpath("wp:post_id", namespaces=self.root.nsmap)))
                title, post = self._format_chapter(chp)
                epub.add_chapter(fid, title, post)
            except:
                print "Error filename: %s" % fid
                traceback.print_exc()

    def _copyimages(self, epub):
        for root, dirs, files in os.walk(self.src_dir):
            if root == self.src_dir:
                pass
            elif os.path.basename(root) == 'images':
                for f in files:
                    epub.add_image(os.path.join(root, f))

    def process(self, epub):
        info = self._get_bloginfo()
        epub.set_info(**info)
        self._exportchapters(epub)
        self._copyimages(epub)


if __name__ == "__main__":
    options, args = getopt.getopt(sys.argv[1:], "h")
    if len(args) < 1:
        print """
Usage : %s srcdir
""" % sys.argv[0]
    else:
        epub = EpubData()
        blog = BlogWordPress(args[0])
        blog.process(epub)
        epub.save()
